class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def pseudoPalindromicPaths(self, root):
        self.ans = 0
        def dfs(node, val):
            val ^= (1 << (node.val - 1))
            if node.left:
                dfs(node.left, val)
            if node.right:
                dfs(node.right, val)
            if not node.left and not node.right:
                if val == 0 or val & (val - 1) == 0:
                    self.ans += 1
        dfs(root, 0)
        return self.ans
